package com.ybkj.daijia.server.websocket.command.impl;

import com.ybkj.daijia.server.model.Admin;
import com.ybkj.daijia.server.model.Area;
import com.ybkj.daijia.server.model.Company;
import com.ybkj.daijia.server.service.AdminService;
import com.ybkj.daijia.server.service.AreaService;
import com.ybkj.daijia.server.service.CompanyService;
import com.ybkj.daijia.server.websocket.WebSocketSessionEx;
import com.ybkj.daijia.server.websocket.WebSocketSessions;
import com.ybkj.daijia.server.websocket.command.Command;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;

@Component
public class ConnectedCommand implements Command {

    private static final Logger logger = LoggerFactory.getLogger(ConnectedCommand.class);

    @Autowired
    private AdminService adminService;

    @Autowired
    private CompanyService companyService;

    @Autowired
    private AreaService areaService;


    @Override
    public void handle(WebSocketSession session, TextMessage message) {

        JSONObject json = new JSONObject(message.getPayload());
        Long userId = json.optLong("userId");

        logger.debug("admin : {} connected ", userId);

        Admin admin = adminService.findOne(userId);
        Company company = companyService.findOne(admin.getCompanyId());
        Area area = areaService.findOne(company.getAreaId());

        WebSocketSessionEx webSocketSessionEx = new WebSocketSessionEx();
        webSocketSessionEx.setAreaID(area.getId());
        webSocketSessionEx.setCityName(company.getCityName());
        webSocketSessionEx.setCompanyID(company.getId());
        webSocketSessionEx.setUserID(admin.getId());
        webSocketSessionEx.setSession(session);
        WebSocketSessions.addSession(session.getId(), webSocketSessionEx);

    }

}
